<?php
//众安开发环境,  iTest:测试环境; uat:预发环境; prd:生产环境
define('ZongAn_Env', 'dev');

class Api
{
    private $_config = [];

    public function __construct()
    {
        $config = require_once __DIR__ . '/zongan_config_' . ZongAn_Env . '.php';
        $this->_config = $config;
    }

    /**
     * 获取地区列表
     * 接口名称：zhongan.cargo.getAllCargoArea
     */
    public function getAllCargoAreaAction()
    {
        $serviceName = "zhongan.cargo.getAllCargoArea";
        $params = ['test' => 1]; //因为对方的接口没有值的话,会报json解析错误
        $version = $this->_config['common_version'];
        $response = $this->getZaCommonDatas($serviceName, $params, $version);
        if (200 != $response['code']) {
            $this->json(4001, sprintf('获取地区列表失败, 失败原因[code:%s|message:%s])', $response['code'], $response['message']));
        }
        $this->json(200, 'SUCCESS', $response['datas']);
    }

    /**
     * 获取通用接口数据
     *
     * 注意:
     *  整车投保: test,uat,prod: 都是 1.0.1
     *  其他接口: test: 1.0.0.9875, prod: 1.0.0
     *
     * @param string $serviceName
     * @param array $params
     * @param $version
     *
     * @return array
     */
    public function getZaCommonDatas($serviceName, $params = [], $version)
    {
        $return = [
            'code'    => 200,
            'message' => '',
        ];
        require_once __DIR__ . '/ZhongAn/ZaCommon/common/ZhongAnApiClient.php';
        try {
            $env = ZongAn_Env;
            $appKey = $this->_config['appKey'];
            $privateKey = $this->_config['privateKey'];
            $_client = new \ZhongAnApiClient($env, $appKey, $privateKey, $serviceName, 'UTF-8', 'RSA', $version);
            $response = $_client->call($params);
        } catch (\Exception $e) {
            $return = [
                'code'    => $e->getCode(),
                'message' => $e->getMessage(),
            ];
        }
        $return['datas'] = $response;
        return $return;
    }


    /**
     * 封装ajax的返回结果
     *
     * @param int $status 状态码
     * @param string $message 提示信息
     * @param array $data 返回值
     *
     * @return mixed
     */
    public function json($status, $message = '', $data = array())
    {
        header('Content-Type:application/json; charset=utf-8');
        $result = [
            'status'  => $status,
            'message' => $message,
            'data'    => $data,
        ];
        echo json_encode($result);
        exit;
    }
}


$api = new Api();
$api->getAllCargoAreaAction();